import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15

Rectangle {
    width: parent.width
    height: parent.height
    color: "#1E1E1E"

    ColumnLayout {
        anchors.fill: parent

        TextArea {
            id: outputArea
            Layout.fillWidth: true
            Layout.fillHeight: true
            readOnly: true
            wrapMode: TextArea.Wrap
            color: "white"  // 设置文本颜色
            background: Rectangle { color: "black" }  // 使用 Rectangle 作为背景
            font.family: "Courier New"
        }

        TextInput {
            id: inputArea
            Layout.preferredHeight: 30
            font.family: "Courier New"
            color: "white"  // 设置输入文本颜色
            focus: true
            onAccepted: {
                if (text.trim() !== "") {
                    terminal.executeCommand(text);
                    text = "";
                }
            }

            Keys.onPressed: {
                if (event.key === Qt.Key_Up) {
                    terminal.historyUp();
                } else if (event.key === Qt.Key_Down) {
                    terminal.historyDown();
                }
            }
        }
    }

    property var commandHistory: []
    property int historyIndex: -1

    function executeCommand(command) {
        outputArea.append(">" + command);
        var process = new QProcess();
        process.start(command);
        process.readyReadStandardOutput.connect(function() {
            var output = process.readAllStandardOutput();
            outputArea.append(output);
        });
        process.readyReadStandardError.connect(function() {
            var error = process.readAllStandardError();
            outputArea.append(error);
        });
        process.finished.connect(function() {
            process.deleteLater();
            commandHistory.push(command);
            historyIndex = commandHistory.length;
        });
    }

    function historyUp() {
        if (historyIndex > 0) {
            historyIndex--;
            inputArea.text = commandHistory[historyIndex];
        }
    }

    function historyDown() {
        if (historyIndex < commandHistory.length - 1) {
            historyIndex++;
            inputArea.text = commandHistory[historyIndex];
        } else {
            historyIndex = commandHistory.length;
            inputArea.text = "";
        }
    }
}
